import logging
from flask.logging import default_handler
from logging.handlers import RotatingFileHandler
from flask import Flask
import config
from exts import db, mail, cache, csrf, avatars
from blueprints.cms import bp as cms_bp
from blueprints.front import bp as front_bp
from blueprints.user import bp as user_bp
from blueprints.media import bp as media_bp
from flask_migrate import Migrate
from sqlalchemy import text
from models import user,post
import commands
from bbs_celery import make_celery
import hooks
import filters
app = Flask(__name__)

# app.config.from_object(config.DevelopmentConfig)
app.config.from_object(config.ProductionConfig)

db.init_app(app)

celery = make_celery(app)

mail.init_app(app)

cache.init_app(app)

csrf.init_app( app)

avatars.init_app(app)

migrate = Migrate(app, db)

app.template_filter('email_hash')(filters.email_hash)

app.register_blueprint(cms_bp)
app.register_blueprint(front_bp)
app.register_blueprint(user_bp)
app.register_blueprint(media_bp)
# with app.app_context():
#     with db.engine.connect() as con:
#         rs = con.execute(text('select 1'))
#         print(rs.fetchone())

# @app.cli.command('my_command')
# def my_command():
#     click.echo('this is my command')

app.before_request(hooks.bbs_before_request)
app.errorhandler(401)(hooks.bbs_401_error)
app.errorhandler(404)(hooks.bbs_404_error)
app.errorhandler(500)(hooks.bbs_500_error)


app.cli.command('create-permission')(commands.create_permission)
app.cli.command('create-role')(commands.create_role)
app.cli.command('create-test-user')(commands.create_test_user)
app.cli.command('create-admin')(commands.create_admin)
app.cli.command('create-admin-batch')(commands.create_admin_batch)
app.cli.command('create-user-batch')(commands.create_user_batch)
app.cli.command('create-board')(commands.create_board)
app.cli.command('create-test-post')(commands.create_test_post)


# app.logger.setLevel(logging.INFO)
# file_hander = logging.FileHandler('bbs.log',encoding='utf-8')
# app.logger.removeHandler(default_handler)
# app.logger.addHandler(file_hander)
#
# class StringFilter(logging.Filter):
#     def filter(self, record):
#         if record.msg.startswith('abc'):
#             return False
#         return True
#
# app.logger.addFilter(StringFilter())
# app.logger.info('abc-test')
# app.logger.info('123-test')

# app.logger.removeHandler(default_handler)
# filehandler=RotatingFileHandler('bbss.log',encoding='utf-8',maxBytes=10*1024, backupCount=10)
# filehandler.setLevel(logging.INFO)
# file_fommatter=logging.Formatter('%(asctime)s-%(levelname)s-%(filename)s-%(message)s[in %(funcName)s-%(lineno)s]')
# filehandler.setFormatter(file_fommatter)
# app.logger.addHandler(filehandler)

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5003)
